package com.example.administrator.bitmapcache;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.LruCache;
import android.widget.ImageView;

import java.io.InputStream;
import java.net.CacheRequest;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Administrator on 2018/8/11.
 */

public class SimpleImageLoader {
    String Url;
    ImageView ImageView;

    private static SimpleImageLoader mLoader;
    private LruCache<String,Bitmap> mLrucache;

    private DiskLruCacheHelper mDiskLruCacheHelper;

    Handler handler = new Handler(){
        public void handleMessage(Message msg){
            Bitmap bitmap = msg.getData().getParcelable("bitmap");
            ImageView.setImageBitmap(bitmap);
            Log.d("Context","加载完成！");
            putBitmapToCache(bitmap,Url);
        }
    };

    public static SimpleImageLoader getInstance(Context context){
        if (mLoader == null){
            synchronized (SimpleImageLoader.class){
                if (mLoader == null){
                    mLoader = new SimpleImageLoader(context);
                }
            }
        }
        return mLoader;
    }

    //用来初始化缓存对象
    private SimpleImageLoader(Context context){
        int maxSize = (int)Runtime.getRuntime().maxMemory()/8;//获取最大的内存空间的1/8
        mLrucache = new LruCache<String,Bitmap>(maxSize){
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount();
            }
        };

        try {
            mDiskLruCacheHelper = new DiskLruCacheHelper(context);
        }
        catch (Exception e){

        }
    }

    //用来加载网络图片
    public void displayImage(ImageView view,String url){
        Url = url;
        Bitmap bitmap = getBitmapFromCache(url);
        if (bitmap!=null){
            view.setImageBitmap(bitmap);
            Log.d("Context","缓存中加载");
        }
        else {
            Log.d("Context","网络加载");
            downloadImage(view,url);
        }
    }

    //从缓存中读取照片
    private Bitmap getBitmapFromCache(String url){
        try {
            if (url != null) {
                if (mLrucache.get(url) != null) {
                    Log.d("Context", "内存！");
                    return mLrucache.get(url);
                } else if (mDiskLruCacheHelper.get(url) != null) {
                    Log.d("Context", "硬盘！");
                    return mDiskLruCacheHelper.getAsBitmap(url);
                }
            }
        }
        catch (Exception e ){

        }
        return null;
    }

    //将下载下来的图片保存到缓存中
    private void putBitmapToCache(Bitmap bitmap,String url){
        if (bitmap!=null){
            mLrucache.put(url,bitmap);
            mDiskLruCacheHelper.put(url,bitmap);
        }
    }

    //下载图片
    private void downloadImage(final ImageView imageView,final String urlStr){
        ImageView = imageView;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(urlStr);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(8000);//连接超时8s
                    conn.setReadTimeout(30000);//设置读取超时30s
                    conn.setRequestMethod("GET");
                    Log.d("Context","getResponseCode:"+conn.getResponseCode());
                    if (conn.getResponseCode() == 200) {
                        InputStream inputStream = conn.getInputStream();
                        Bitmap bitmap= BitmapFactory.decodeStream(inputStream);

                        Message message = new Message();
                        Bundle bundle = new Bundle();
                        bundle.putParcelable("bitmap",bitmap);
                        message.setData(bundle);
                        handler.sendMessage(message);
                    }
                    //状态非200
                    else {
                        Log.d("Context","失败！");
                    }
                }
                catch (Exception e){
                    Log.d("Context","获取广告图片出错："+e);
                }
            }
        }).start();
    }

}
